package org.easy.sse.dto;


import com.alibaba.fastjson2.JSON;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SseHttpServletResponse {

    private final HttpServletResponse httpServletResponse;

    public SseHttpServletResponse(HttpServletResponse httpServletResponse) {
        this.httpServletResponse = httpServletResponse;
        this.httpServletResponse.setContentType("text/event-stream");
        this.httpServletResponse.setCharacterEncoding("UTF-8");
        this.httpServletResponse.setStatus(200);
    }

    public void writeStart() {
        doWrite(SseFlowDto.start());
    }

    public void writeInit(SseFlowDto init) {
        doWrite(init);
    }

    public void writeEvent(SseFlowDto sseFlowDto) {
        doWrite(sseFlowDto);
    }

    public void writeFailure() {
        doWrite(SseFlowDto.failure());
    }

    public void writeFailure(SseFlowDto sseFlowDto) {
        doWrite(SseFlowDto.failure(sseFlowDto));
    }


    public void writeStop() {
        doWrite(SseFlowDto.stop());
    }

    public void writeClose() {
        doWrite(SseFlowDto.close());
    }

    private void doWrite(SseFlowDto sseFlowDto) {
        if (httpServletResponse == null) {
            return;
        }
        try {
            httpServletResponse.getWriter().write(warpResult(sseFlowDto));
            httpServletResponse.getWriter().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String getHeader(String name) {
        return httpServletResponse.getHeader(name);
    }

    private static String warpResult(SseFlowDto sseFlowDto) {
        return "data:" + JSON.toJSONString(sseFlowDto) + "\n\n";
    }


}
